package org.uninova.mobis.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.uninova.mobis.db.UserDBConnector;

import cc.curiouscat.types.User;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * Servlet implementation class AndroidAppRedirectServlet
 */
@WebServlet("/AndroidAppRedirect")
public class AndroidAppRedirectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AndroidAppRedirectServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response) ;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response) ;
	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) {
		String ccToken = request.getParameter("ccToken") ;
		
		String option = request.getParameter("option") ;
		
		if (ccToken != null && !ccToken.equals("")) {
			//TODO: Check ccToken here, before calling GetResRobotRoutesJSON
			
			UserDBConnector userConnector = new UserDBConnector() ;
			
			boolean userExists = userConnector.userExists(ccToken) ;
			
			try {
				if (!userExists) {
					
					String prophetURL = "http://shodan.ijs.si/ProphetServer/getUser?CCVersion=0.1.2013.05.29&oauth_token=" + ccToken ;
					URLConnection con = new URL(prophetURL).openConnection() ;
					//con.setDoOutput(true) ;
					
					InputStream prophetResponse = con.getInputStream() ;
					Reader reader = new InputStreamReader(prophetResponse) ;
					
					Gson gson = new Gson() ;
					JsonParser parser = new JsonParser() ;
					JsonElement elem = parser.parse(reader).getAsJsonObject().get("response") ;
					
					User user = gson.fromJson(elem, User.class) ;
					
					userConnector.createUser(user) ;
				}
				
				if (option.equals("getDirections")) {
					response.sendRedirect("/MobisRoutePlannerV0.3/GetDirectionsRoutino") ;
					return ;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
